package com.zhx.sweet.authentication.mobile;


import com.zhx.sweet.common.constants.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 短信登录拦截器
 * @author zhanghaixuan
 * 2017年11月04日22:22:57
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_FORM_MOBLIE= "mobile";


    private String moblieParameter = SPRING_SECURITY_FORM_MOBLIE;

    private boolean postOnly = true;

    public SmsCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        System.out.println("进入 SmsCodeAuthenticationFilter attemptAuthentication");

        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String mobile = this.obtainMoblie(request);

            System.out.println("获取的mobile是 " + mobile);

            if (mobile == null) {
                mobile = "";
            }

            mobile = mobile.trim();
            SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    protected String obtainMoblie(HttpServletRequest request) {
        return request.getParameter(this.moblieParameter);
    }

    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public String getMoblieParameter() {
        return moblieParameter;
    }

    public void setMoblieParameter(String moblieParameter) {
        Assert.hasText(moblieParameter, "moblie parameter must not be empty or null");
        this.moblieParameter = moblieParameter;
    }


    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}










